<?php
namespace Goatherd\Content\Engine\Reader;

use Goatherd\Content\Engine\Reader\Buffer\IBuffer;

use Goatherd\Content\Engine\Queue\IItem;

/**
 * Buffered reader implementation.
 *
 * @category ContentEngine
 * @package Goatherd\Content\Engine
 * @subpackage Reader
 */
abstract class AbstractBufferedReader
extends AbstractReader
implements IBufferedReader
{
    /**
     *
     * @var IBuffer
     */
    protected $_buffer = null;

    /**
     *
     * @param IBuffer $buffer
     * @return \Goatherd\Content\Engine\Reader\AbstractReader
     */
    public function setBuffer(IBuffer $buffer)
    {
        $this->_buffer = $buffer;

        return $this;
    }

    /**
     *
     * @return IBuffer
     */
    public function getBuffer()
    {
        return $this->_buffer;
    }

    /**
     * (non-PHPdoc)
     * @see Goatherd\Content\Engine\Reader.IReader::get()
     */
    public function get(IItem $item)
    {
        $buffer = $this->getBuffer();
        $buffer->activeReader($this);

        if ($buffer->hasResource($item)) {
            $resource = $buffer->getResource($item);
        } else {
            $resource = $this->getResource($item);
            $buffer->setResource($item, $resource);
        }

        return ResourceContainer::create( $resource );
    }
}